<template>
  <div class="incoming-call-module">
    <div class="incoming-call-pop" v-for="call in calls" :key="call.callId">
      <CallingPop :call="call" :handleCallRing="handleCallRing"/>
    </div>
  </div>
</template>

<script>
import CallingPop from "@/components/bottom/CallingPop.vue";
import {getCache} from "@/utils/local_cache";
import {reportCallRespond, subCallReply, subCallRing, unSubCallReply, unSubCallRing} from "@/api/nats/private_chat";
import {R} from "@/utils/R";

export default {
  name: "IncomingCalling",
  components: {CallingPop},
  inject: ['callCommand'],
  props: {
    singleCallRingRespond: {
      type: Function
    },
    confirmHangup: {
      type: Function
    }
  },
  data() {
    return {
      /**
       * {
       *    type: this.callType.single,
       *    callId,
       *    callee,
       *    caller
       *  }
       */
      calls: [],
      user: null
    }
  },
  methods: {
    receivedCallRing(callRing) {
      this.$message.info('有新的通话邀请')
      this.calls.push(callRing.call)
      return R.ok()
    },
    receivedCallRingReply(reply){
      const {command} = reply
      if (command === this.callCommand.cancel) {
        const {callId , caller} = reply.call;
        this.calls = this.calls.filter(item => item.callId !== callId)
        this.$message.info(`${caller.nickname}取消通话`)
      }
    },
    async handleCallRing(call , command){
      const {caller, callee, callId} = call
      const respond = {
        command,
        call
      }
      if (command === this.callCommand.agree) {
        if (!await this.confirmHangup()) {
          return
        }
      }
      const result = await this.singleCallRingRespond(respond);
      if (result) {
        this.calls = this.calls.filter(item => item.callId !== callId)
        reportCallRespond(callee.id , caller.id , respond);
      }
    },
  },
  mounted() {
    this.user = getCache('user');
    subCallRing(this.user.id, this.receivedCallRing);
    subCallReply(this.user.id, this.receivedCallRingReply);
  },
  beforeDestroy() {
    unSubCallRing(this.user.id);
    unSubCallReply(this.user.id);
  }
}
</script>

<style scoped>

.incoming-call-module {
  position: fixed;
  right: 310px;
  bottom: 10px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.incoming-call-pop {
  width: 150px;
  height: 60px;
  border-radius: 20px;
  background-color: inherit;
  align-items: center;
  text-align: center;
  border: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  animation: breathe 2s ease-in-out infinite;
}

@keyframes breathe {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}


</style>